from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework import status
from .models import *
from .serializers import Courses_serializers
from .spider import land_sise_get_info


# Create your views here.


@api_view(['GET', 'PUT'])
def Course(request):
    """
    PUT:
    爬取课表
    """
    data = request.data
    StudentID = data['StudentID']
    if request.method == 'GET':
        s = Courses_serializers(Courses.objects.filter(StudentID=StudentID), many=True)
        return Response(s.data, status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        Password = data['Password']
        user = UserInfo.objects.filter(StudentID=StudentID)[0]
        a = land_sise_get_info(url='http://class.seig.edu.cn:7001/sise/module/student_schedular/student_schedular.jsp',
                               user=StudentID,
                               pw=Password)
        if a:
            for i in a:
                week = i[0]
                time = i[1]
                course = i[2]
                class_id = i[3]
                class_teacher = i[4]
                class_week = i[5]
                claas_room = i[6]
                Courses.objects.create(StudentID=user, CourseName=course, StartTime=time[:5], Teacher=class_teacher, ClassWeek=class_week, EndTime=time[8:], Week=week, room=claas_room, Class=class_id)
        return Response(status=status.HTTP_200_OK)
    return Response(status=status.HTTP_400_BAD_REQUEST)
